

class DownloaderProxy(object):
    def __init__(self, host, port, username, password):
        self.host = host
        self.port = port
        self.username = username
        self.password = password

class CrawlRequest(object):
    """
    CrawlRequest is a python mapping with org.hong.monkey.crawl.CrawlRequest in scala
    >>> jrequest = sc._jvm.org.hong.monkey.crawl.CrawlRequest("http://www.baidu.com", None, None, "60s", None, None, 0, "0s", "0s", "0s", "org.hong.monkey.crawl.HttpClientDownloader")
    """
    def __init__(self, link,
                 cookies = None,
                 headers = None,
                 timeout = "60s",
                 proxy = None,
                 carryData = None,
                 retryTimes = 0,
                 delayTime = "0s",
                 randomDelayMinLimitTime = "0s",
                 randomDelayMaxLimitTime = "0s",
                 downloaderClass = "org.hong.monkey.crawl.HttpClientDownloader"):

        self.link = link
        self.cookies = cookies
        self.headers = headers
        self.timeout = timeout
        self.proxy = proxy
        self.carryData = carryData
        self.retryTimes = retryTimes
        self.delayTime = delayTime
        self.randomDelayMinLimitTime = randomDelayMinLimitTime
        self.randomDelayMaxLimitTime = randomDelayMaxLimitTime
        self.downloaderClass = downloaderClass

    def download(self):
        return self.jrequest().download()

    def jrequest(self):
        from pymonkey.java_gateway import launch_gateway
        _gateway = launch_gateway()

        jheaders = None
        if self.headers != None:
            jheaders = _gateway._jvm.org.hong.monkey.crawl.Headers()
            for key in self.headers.keys:
                jheaders.put(key, self.headers[key])

        jproxy = None
        if self.proxy != None:
            jproxy = _gateway.jvm.org.hong.monkey.crawl.HttpDownloaderProxy(self.proxy.host, self.proxy.port,
                                                                        self.proxy.username, self.proxy.password)

        return _gateway.jvm.org.hong.monkey.crawl.CrawlRequest(self.link, self.cookies, jheaders, self.timeout, jproxy,
                                                         self.carryData, self.retryTimes, self.delayTime,
                                                         self.randomDelayMaxLimitTime, self.randomDelayMinLimitTime,
                                                         self.downloaderClass)

